<template>
    <div class="role-permission-container">
      <!-- 搜索栏 -->
      <div class="search-container">
        <el-form :model="searchForm" class="search-form" label-width="100px">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="角色名称">
                <el-select
                  v-model="searchForm.roleId"
                  filterable
                  clearable
                  placeholder="请选择角色"
                  @change="handleRoleChange"
                  :loading="roleLoading"
                >
                  <el-option
                    v-for="role in roleList"
                    :key="role.roleId"
                    :label="role.roleName"
                    :value="role.roleId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="权限名称">
                <el-input
                  v-model="searchForm.permissionName"
                  placeholder="请输入权限名称"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="6" class="search-buttons">
              <el-button type="primary" @click="handleSearch" :loading="searchLoading">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
  
      <!-- 主内容区 -->
      <div class="main-content">
        <!-- 权限树 -->
        <div class="permission-tree">
          <div class="tree-header">
            <span>权限列表</span>
            <el-button 
              type="primary" 
              size="mini" 
              @click="saveRolePermissions"
              :loading="saveLoading"
              :disabled="!currentRole"
            >
              保存权限
            </el-button>
          </div>
          <el-tree
            ref="permissionTree"
            :data="permissionTreeData"
            show-checkbox
            node-key="permissionId"
            :props="treeProps"
            :default-expand-all="true"
            :filter-node-method="filterNode"
            @check="handleCheckChange"
            v-loading="treeLoading"
          />
        </div>
  
        <!-- 已选权限表格 -->
        <div class="selected-permissions">
          <div class="table-header">
            <span>已选权限 ({{ selectedPermissions.length }})</span>
            <el-button 
              type="danger" 
              size="mini" 
              @click="handleBatchRemove"
              :disabled="!selectedPermissions.length || !currentRole"
              :loading="removeLoading"
            >
              批量移除
            </el-button>
          </div>
          <el-table
            :data="selectedPermissions"
            border
            height="100%"
            @selection-change="handleTableSelection"
            v-loading="tableLoading"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="permissionId" label="权限ID" width="100" align="center" />
            <el-table-column prop="permissionName" label="权限名称" />
            <el-table-column prop="permissionCode" label="权限编码" />
            <el-table-column label="操作" width="100" align="center">
              <template #default="{ row }">
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="removePermission(row.permissionId)"
                    auto-insert-space:disabled="!currentRole"
                  >
                移除
                </el-button>
            </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import request from '@/utils/request'
  import { ElMessage, ElMessageBox } from 'element-plus'
  
  export default {
    name: 'RolePermission',
    data() {
      return {
        searchForm: {
          roleId: null,
          permissionName: ''
        },
        roleList: [],
        permissionTreeData: [],
        treeProps: {
          children: 'children',
          label: 'permissionName'
        },
        selectedPermissions: [],
        currentRole: null,
        tableSelection: [],
        // 加载状态
        roleLoading: false,
        treeLoading: false,
        tableLoading: false,
        searchLoading: false,
        saveLoading: false,
        removeLoading: false
      }
    },
    created() {
      this.fetchRoles()
      this.fetchPermissions()
    },
    methods: {
      // 获取角色列表
      async fetchRoles() {
        this.roleLoading = true
        try {
            const res = await request.get('/role/list')
            console.log('角色接口返回数据:', res) // 调试日志
            
            if (res.code === 200) {
            // 修改这里，从res.data.records获取数据
            this.roleList = res.data.records || []
            console.log('处理后的角色列表:', this.roleList) // 调试日志
            } else {
            ElMessage.error(res.message || '获取角色列表失败')
            }
        } catch (error) {
            console.error('获取角色列表失败:', error)
            ElMessage.error('获取角色列表失败，请检查网络连接')
        } finally {
            this.roleLoading = false
        }
    },
  
      // 获取权限树结构
      async fetchPermissions() {
        this.treeLoading = true
        try {
          const res = await request.get('/permission/tree')
          if (res.code === 200) {
            this.permissionTreeData = res.data
          } else {
            ElMessage.error(res.message || '获取权限列表失败')
          }
        } catch (error) {
          console.error('获取权限列表失败:', error)
          ElMessage.error('获取权限列表失败，请检查网络连接')
        } finally {
          this.treeLoading = false
        }
      },
  
      // 角色选择变化处理
      async handleRoleChange(roleId) {
        if (!roleId) {
          this.currentRole = null
          this.resetPermissionSelection()
          return
        }
  
        this.currentRole = this.roleList.find(role => role.roleId === roleId)
        this.tableLoading = true
        
        try {
          const res = await request.get('/rolePermission/permissionsByRole', {
            params: { roleId }
          })
          
          if (res.code === 200) {
            const permissionIds = res.data || []
            this.$refs.permissionTree.setCheckedKeys(permissionIds)
            this.updateSelectedPermissions(permissionIds)
          } else {
            ElMessage.error(res.message || '获取角色权限失败')
          }
        } catch (error) {
          console.error('获取角色权限失败:', error)
          ElMessage.error('获取角色权限失败，请检查网络连接')
        } finally {
          this.tableLoading = false
        }
      },
  
      // 更新已选权限
      updateSelectedPermissions(permissionIds) {
        const flatPermissions = this.flattenTree(this.permissionTreeData)
        this.selectedPermissions = flatPermissions.filter(permission => 
          permissionIds.includes(permission.permissionId)
        )
      },
  
      // 扁平化权限树
      flattenTree(tree, result = []) {
        tree.forEach(node => {
          result.push({
            permissionId: node.permissionId,
            permissionName: node.permissionName,
            permissionCode: node.permissionCode
          })
          if (node.children && node.children.length) {
            this.flattenTree(node.children, result)
          }
        })
        return result
      },
  
      // 节点过滤
      filterNode(value, data) {
        if (!value) return true
        return data.permissionName.toLowerCase().includes(value.toLowerCase())
      },
  
      // 搜索处理
      handleSearch() {
        this.searchLoading = true
        try {
          this.$refs.permissionTree.filter(this.searchForm.permissionName)
        } finally {
          this.searchLoading = false
        }
      },
  
      // 重置搜索
      resetSearch() {
        this.searchForm = { roleId: null, permissionName: '' }
        this.resetPermissionSelection()
        this.$refs.permissionTree.filter('')
      },
  
      // 重置权限选择
      resetPermissionSelection() {
        this.$refs.permissionTree.setCheckedKeys([])
        this.selectedPermissions = []
        this.currentRole = null
      },
  
      // 权限勾选变化
      handleCheckChange(checkedNodes, checkedKeys) {
        this.updateSelectedPermissions(checkedKeys.checked)
      },
  
      // 移除单个权限
      removePermission(permissionId) {
        this.$refs.permissionTree.setChecked(permissionId, false)
      },
  
      // 批量移除权限
      async handleBatchRemove() {
        if (!this.tableSelection.length) {
            return ElMessage.warning('请选择要移除的权限')
        }

        try {
            await ElMessageBox.confirm(`确认移除选中的 ${this.tableSelection.length} 个权限吗？`, '提示', { 
            type: 'warning' 
            })

            this.removeLoading = true
            const permissionIds = this.tableSelection.map(item => item.permissionId)
            
            // 方案1：推荐格式（JSON Body + URL参数）
            const res = await request.post('/rolePermission/batchDelete', 
            permissionIds, // 直接传数组
            {
                params: { roleId: this.currentRole.roleId }
            }
            )

            // 方案2：备用格式（完整JSON对象）
            /* const res = await request.post('/rolePermission/batchDelete', {
            roleId: this.currentRole.roleId,
            permissionIds: permissionIds
            }) */

            if (res.code === 200) {
            ElMessage.success('权限移除成功')
            await this.handleRoleChange(this.currentRole.roleId) // 刷新权限
            } else {
            ElMessage.error(res.message || '权限移除失败')
            }
        } catch (error) {
            if (error !== 'cancel') {
            console.error('错误详情:', error.response?.data || error) // 打印详细错误
            ElMessage.error(`移除失败: ${error.message}`)
            }
        } finally {
            this.removeLoading = false
        }
      },
  
      // 保存权限
      async saveRolePermissions() {
        if (!this.currentRole) {
            return ElMessage.warning('请先选择角色')
        }

        const permissionIds = this.$refs.permissionTree.getCheckedKeys()
        if (permissionIds.length === 0) {
            return ElMessage.warning('请至少选择一个权限')
        }

        try {
            this.saveLoading = true
            console.log('准备提交的数据:', {  // 调试日志
            roleId: this.currentRole.roleId,
            permissionIds
            })

            const res = await request.post('/rolePermission/batchAdd', 
            permissionIds, // 直接传递数组作为请求体
            {
                params: { // 通过URL参数传递roleId
                roleId: this.currentRole.roleId 
                }
            }
            )

            if (res.code === 200) {
            ElMessage.success('权限保存成功')
            } else {
            ElMessage.error(res.message || '权限保存失败')
            }
        } catch (error) {
            console.error('保存失败详情:', error.response || error) // 详细错误日志
            ElMessage.error(`保存失败: ${error.message}`)
        } finally {
            this.saveLoading = false
        }
      },
  
      // 表格选择变化
      handleTableSelection(selection) {
        this.tableSelection = selection
      }
    }
  }
  </script>
  
  <style scoped>
  /* 原有样式保持不变 */
  .role-permission-container {
    padding: 20px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    height: calc(100vh - 120px);
    display: flex;
    flex-direction: column;
  }
  
  .search-container {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
  
  .search-buttons {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    height: 100%;
  }
  
  .main-content {
    display: flex;
    flex: 1;
    gap: 20px;
    overflow: hidden;
  }
  
  .permission-tree,
  .selected-permissions {
    flex: 1;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 10px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  
  .tree-header,
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding: 0 10px;
  }
  
  .tree-header span,
  .table-header span {
    font-weight: bold;
    color: #333;
  }
  
  .el-tree,
  .el-table {
    flex: 1;
    overflow: auto;
  }
  
  .el-table__fixed-right {
    right: 0;
  }
  
  /* 响应式调整 */
  @media (max-width: 992px) {
    .main-content {
      flex-direction: column;
    }
  
    .permission-tree,
    .selected-permissions {
      flex: none;
      height: 300px;
      margin-top: 20px;
    }
  }
  </style>